//
//  RecommendViewController.m
//  AroundTheWorld
//
//  Created by IfelseGo on 16/5/14.
//  Copyright © 2016年 IfelseGo an. All rights reserved.
//

#import "RecommendViewController.h"
#import "ANScrollView.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

#import "RecommendDataModel.h"
#import "CheckinModel.h"
#import "SlideModel.h"
#import "RecoummendScorollVC.h"
#import "SubjectModel.h"
#import "Discount_SubjectModel.h"
#import "DiscountModel.h"
#import "RecoummendHotelVC.h"

#import "RecoummendQiandaoVC.h"
#import "RecoummendKJNVC.h"

#import "MyCollectionViewCell.h"
#import "SubjectTableViewCell.h"
#import "DiscountableViewCell.h"
#import "HotTravellTableViewCell.h"

#import "SubjectBgImageTableViewCell.h"
#import "SubjectTextTableViewCell.h"
#import "SubjectCollectionViewCell.h"
#import "SubjectMoreVC.h"
#import "SubjectHotVC.h"

#import "DiscountBgImageTableViewCell.h"
#import "DiscountSmallImageTableViewCell.h"
#import "DiscounTextTableViewCell.h"
#import "DiscountSmallImageCollectionViewCell.h"
#import "DiscountHotVC.h"
#import "DiscountMoreVC.h"
#import "DiscountBGHotVC.h"

#import "HotTravelViewController.h"
#import "GuideViewController.h"
#import "DestnationCountryDiscountSuperModel.h"


#import "MJRefresh.h"
#import "UIScrollView+MJRefresh.h"
#import "MJRefreshHeaderView.h"
#import "MJRefreshFooterView.h"

#import "DataBaseHandle.h"

//静态变量 标识符
static NSString *const subjectReuse = @"subjectReuse";
static NSString *const subTextReuse = @"SubtextReuse";
static NSString *const subBgReuse = @"SubBgReuse";
static NSString *const disBgReuse = @"disBgReuse ";
static NSString *const disSmallReuse = @"disSmallReuse";
static NSString *const disTextReuse = @"disTextReuse";
static NSString *const discounReuse = @"discounReuse";
static NSString *const hotTravelReuse = @"hotTravelReuse";

@interface RecommendViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *myTabelView;
@property (nonatomic, assign) NSInteger myPageNumber;
@property (nonatomic, strong) NSMutableArray *myArray;
@property (nonatomic, strong) NSMutableArray *allArray;
@property (nonatomic, strong) NSMutableArray *discountArrayM;

//headerButton
@property (nonatomic, strong) UIButton *KJNButton;
@property (nonatomic, strong) UIButton *QZKButton;
@property (nonatomic, strong) UIButton *DJDButton;
@property (nonatomic, strong) UIButton *LTZButton;
@property (nonatomic, strong) UIButton *SignButton;
@property (nonatomic, strong) ANScrollView *slideView;
@property (nonatomic, strong) RecommendDataModel *datamodel;

@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];

//    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBarHidden = NO;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, -5, WIDTH - 120, 25)];
    label.text = @"➢  搜索目的地、帖子、特价、穷游er ";
    
    label.backgroundColor = [UIColor colorWithRed:58 / 255.0 green:160 / 255.0 blue:130 / 255.0 alpha:0.8];
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = 12;
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
    
    self.myTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 55) style:UITableViewStylePlain];
    self.myTabelView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.myTabelView];
    
    //成为代理人
    self.myTabelView.delegate = self;
    self.myTabelView.dataSource = self;
    
    //注册
    [self.myTabelView registerClass:[SubjectTableViewCell class] forCellReuseIdentifier:subjectReuse];
    [self.myTabelView registerClass:[SubjectBgImageTableViewCell class] forCellReuseIdentifier:subBgReuse];
    [self.myTabelView registerClass:[SubjectTextTableViewCell class] forCellReuseIdentifier:subTextReuse];
    
    [self.myTabelView registerClass:[DiscountBgImageTableViewCell class] forCellReuseIdentifier:disBgReuse];
    [self.myTabelView registerClass:[DiscountSmallImageTableViewCell class] forCellReuseIdentifier:disSmallReuse];
    [self.myTabelView registerClass:[DiscounTextTableViewCell class] forCellReuseIdentifier:disTextReuse];
    
    [self.myTabelView registerClass:[HotTravellTableViewCell class] forCellReuseIdentifier:hotTravelReuse];
    
    //添加头视图
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 420)];
    headerView.backgroundColor = [UIColor clearColor];
    self.myTabelView.tableHeaderView = headerView;
    
    [self getData];
    
    //轮播图
    [self showGuideIfNecessary];
    
    //刷新
    [self refreshTests];
    
    //夜间模式
    self.view.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff,0xCFCFCF);
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorPickerWithRGB(0x3AA082,0xCFCFCF);
    
    self.navigationItem.leftBarButtonItem= [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(buttonAtcion:)];
     [self.dk_manager dawnComing];
    
    //搜索
//    [self loadSearchBar];
}

- (void)showGuideIfNecessary
{
    if ([GuideViewController shouldShowGuide]) {
        GuideViewController *controller = [[GuideViewController alloc] initWithNibName:nil bundle:nil];
        [self presentViewController:controller animated:NO completion:nil];
    }
}
//夜间模式判断
- (void)buttonAtcion:(UIBarButtonItem *)item{
    if ([self.dk_manager.themeVersion isEqualToString:DKThemeVersionNight]) {
        item.image = [[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        NSLog(@"白天");
        [self.dk_manager dawnComing];
    } else {
        NSLog(@"晚上");
        item.image = [[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.dk_manager nightFalling];
    }
}

//data
-(void)getData{
    self.recommendArrayM = [NSMutableArray array];
    self.HotTravelNotesArrayM = [NSMutableArray array];
    self.allArray = [NSMutableArray array];
    
    DataHandler *handler1 = [[DataHandler alloc] init];
    DataHandler *handler2 = [[DataHandler alloc] init];
   
    [handler1 getRecommend:^(id result) {
        self.HUB = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self.HUB show:YES];
        self.HUB.labelText = @"loading...";
        
        self.recommendArrayM = [NSMutableArray arrayWithArray:result];
        self.datamodel = [self.recommendArrayM objectAtIndex:0];
        self.allArray = self.datamodel.slide;
        self.discountArrayM = self.datamodel.discount;
        
        [MBProgressHUD hideHUDForView:self.view animated:YES]; //菊花条
        
        [self addANSlideImage];
        [self addButtonBounds];
        [self.myTabelView reloadData];
    } failedHandler:^(NSError *error) {
        
    }];
    
    [handler2 getHotTravelNotes:1 SucceedHandler:^(id result) {
        self.HUB = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self.HUB show:YES];
        self.HUB.labelText = @"loading...";
        self.HotTravelNotesArrayM = [NSMutableArray arrayWithArray:result];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES]; //菊花条
        [self.myTabelView reloadData];
    } failedHandler:^(NSError *error) {
        
    }];
 }

//添加搜索按钮
-(void)addSearch
{
    //背景颜色
     UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 70)];
    view.backgroundColor = [UIColor colorWithRed:66 /255.0 green:168 / 255.0 blue:115 / 255.0 alpha:1.0];
    [self.view addSubview:view];

    //添加搜索按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(60, 20, WIDTH - 80, 50);
    [button setImage:[UIImage imageNamed:@"btn_soushuo1"] forState:UIControlStateNormal];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(naveritemAction) forControlEvents:UIControlEventTouchUpInside];
 }

//搜索出发方法
- (void)naveritemAction
{
    
}
//添加看锦囊等
-(void)addButtonBounds{
    //看锦囊背景
    UILabel *backLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 220, WIDTH, 130)];
    backLabel.backgroundColor = [UIColor colorWithRed:219 / 255.0 green:227 / 255.0 blue:233 / 255.0 alpha:1.0];
    [self.myTabelView addSubview:backLabel];
    //分隔灰色条 1
    UILabel *grayLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 350, WIDTH, 10)];
    grayLabel1.backgroundColor = [UIColor colorWithRed:232 / 255.0 green:230 / 255.0 blue:233 / 255.0 alpha:1.0];
    [self.myTabelView addSubview:grayLabel1];
    //button 文字 + icon
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myButton.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff,0xCFCFCF);
//    myButton.backgroundColor = [UIColor whiteColor];
    myButton.frame = CGRectMake(0, 365, WIDTH, 50);
    [myButton setTitle:@"点击我去过的目的地,帮助更多穷游er      >" forState:UIControlStateNormal];
    [myButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.myTabelView addSubview:myButton];
    
    UIImageView *iconImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabbar-shequ2_32x32.png"]];
    iconImageV.frame = CGRectMake(18, 380, 20, 20);
    [self.myTabelView addSubview:iconImageV];
    self.KJNButton = [self addIcon:@"看锦囊" heghtNumber:1];
    self.KJNButton.backgroundColor = [UIColor clearColor];
    [self.KJNButton setBackgroundImage:[UIImage imageNamed:@"btun-1.png"] forState:UIControlStateNormal];
    [self.KJNButton addTarget:self action:@selector(KJNButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.QZKButton = [self addIcon:@"抢折扣" heghtNumber:2];
    self.KJNButton.backgroundColor = [UIColor clearColor];
    [self.QZKButton setBackgroundImage:[UIImage imageNamed:@"btn-2.png"] forState:UIControlStateNormal];
    [self.QZKButton addTarget:self action:@selector(QZKButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.DJDButton = [self addIcon:@"订酒店" heghtNumber:3];
    self.KJNButton.backgroundColor = [UIColor clearColor];
    [self.DJDButton setBackgroundImage:[UIImage imageNamed:@"btn-3.png"] forState:UIControlStateNormal];
    [self.DJDButton addTarget:self action:@selector(DJDButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.LTZButton = [self addIcon:@"旅途中" heghtNumber:4];
    self.KJNButton.backgroundColor = [UIColor clearColor];
    [self.LTZButton setBackgroundImage:[UIImage imageNamed:@"btun-4.png"] forState:UIControlStateNormal];
    
    //签到按钮
    self.SignButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.SignButton.frame = CGRectMake(330, 30, 40, 50);
    self.SignButton.backgroundColor = [UIColor clearColor];
    [self.myTabelView  addSubview:self.SignButton];
    self.SignButton.alpha = 1.0;
        [self.SignButton setBackgroundImage:[UIImage imageNamed:@"btn-qiandao.png"] forState:UIControlStateNormal];
    [self.SignButton setTitle:@"" forState:UIControlStateNormal];
    [self.SignButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    self.SignButton.titleLabel.font = [UIFont systemFontOfSize:12] ;
    [self.SignButton addTarget:self action:@selector(qiandaoButtonAction) forControlEvents:UIControlEventTouchUpInside];
    

}
-(UIButton *)addIcon:(NSString *)labelName heghtNumber:(NSInteger )heght{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor grayColor];
    button.frame = CGRectMake(25 + (60 + 40) * (heght - 1), 235, 60, 60);
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 30;
    [self.myTabelView addSubview:button];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(25 + (60 + 40) * (heght - 1), 310 ,60, 25)];
    label.text = labelName;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:14];
    [self.myTabelView addSubview:label];
    return button;
}
//1.Button触发方法
- (void)qiandaoButtonAction{
    RecoummendQiandaoVC *qdVC = [[RecoummendQiandaoVC alloc] init];
    [self presentViewController:qdVC animated:YES completion:^{
        
    }];
}
//看锦囊
- (void)KJNButtonAction{
    RecoummendKJNVC *kjnVC = [[RecoummendKJNVC alloc] init];
    [self presentViewController:kjnVC animated:YES completion:^{
        
    }];
}

//1-2抢折扣
- (void)QZKButtonAction{
    DiscountMoreVC *rootVC = [[DiscountMoreVC alloc] init];
    [self presentViewController:rootVC animated:YES completion:^{
    }];
}

- (void)DJDButtonAction{
    RecoummendHotelVC *hotelVC = [[RecoummendHotelVC alloc] init];
    [self.navigationController pushViewController:hotelVC animated:YES];
}

//分区的个数
-(NSInteger )numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

//分区头高度
-(CGFloat )tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section
{
    return 50;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //背景颜色
    UIView *view = [UIView new];
    view.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff,0xCFCFCF);
//    view.backgroundColor = [UIColor whiteColor];
    
    //分隔线
    UILabel *FGX = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH , 10)];
    FGX.backgroundColor = [UIColor colorWithRed:232 / 255.0 green:230 / 255.0 blue:233 / 255.0 alpha:1.0];
    [view addSubview:FGX];
    
    //标题
    UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, WIDTH -30 , 30)];
    [view addSubview:text];
    text.textColor = [UIColor grayColor];
    
    //文字定义
    if (section == 0) {
        text.text = @"发现下一站";
     }
    if (section == 1) {
        text.text = @"抢特价折扣";
    }else
    {
    text.text = @"看热门游记";
    }
    return view;
}

//cell高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //分区1
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 170;
        }
        if (indexPath.row == 1) {
            return 140;
        }
        return 60;
    }
    //分区2
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 170;
        }
        if (indexPath.row == 1) {
            return 450;
        }
        return 60;
    }
    //分区3
    return 98;
}

//cell数
-(NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
         return 3;
    }
    if (section == 1) {
        return 3;
    }
    return self.HotTravelNotesArrayM.count;
}

//建cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //分区1
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            SubjectBgImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:subBgReuse];
            SubjectModel *bgModel = [self.datamodel.subject objectAtIndex:0];
            [cell.myBgImageView sd_setImageWithURL:[NSURL URLWithString:bgModel.photo] placeholderImage:nil];
             return cell;
        }
        if (indexPath.row == 1) {
           SubjectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:subjectReuse];
           cell.subjectArray = self.datamodel.subject;
            //B--->A 点击PIC传值
            cell.myBlock = ^(NSString *url, NSString *title){
                SubjectHotVC *subjectHotVC = [[SubjectHotVC alloc] init];
                subjectHotVC.myUrl = url;
                subjectHotVC.myTitle = title;
            [self presentViewController:subjectHotVC animated:YES completion:^{
                
            }];
            };
             return cell;
        }
        if (indexPath.row == 2) {
            SubjectTextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:subTextReuse];
            return cell;
        }
    }
    //分区2
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            DiscountBgImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:disBgReuse];
            cell.myDisSubModel = [self.datamodel.discount_subject objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            return cell;
        }
        if (indexPath.row == 1) {
            DiscountSmallImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:disSmallReuse];
            cell.smallArray = self.datamodel.discount;
            //B--->A 点击PIC传值
            cell.myBlock = ^(NSString *discountId, NSInteger indexPath){
                DiscountHotVC *discountHotVC = [[DiscountHotVC alloc] init];
                discountHotVC.discountId = discountId;
                [self presentViewController:discountHotVC animated:YES completion:^{
                    
                }];
                discountHotVC.myFaveriteIDBlock = ^(BOOL isFavorite, NSString *discountId){
                    if (isFavorite == YES) {
                        //用户名为空的时候点击登陆, 不是空的时候收藏
                        NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
                        NSString *userName = [defa objectForKey:@"userName"];
                        DiscountModel *model = [self.discountArrayM objectAtIndex:indexPath];
                        [[DataBaseHandle shareDataBaseHandle] insertDiscount:model withUserName:userName withSQname:@"discount"];
                    }
                };
            };
            return cell;
        }
        if (indexPath.row == 2) {
            DiscounTextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:disTextReuse];
            return cell;
        }
    }
    //分区3
    HotTravellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:hotTravelReuse];
    HotTravelNotesModel *model = [self.HotTravelNotesArrayM objectAtIndex:indexPath.row];
    cell.hotModel = model;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

//CELL触发方法  
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            SubjectHotVC *subjectHotVC = [[SubjectHotVC alloc] init];
            SubjectModel *bgModel = [self.datamodel.subject objectAtIndex:0];
            subjectHotVC.myTitle = bgModel.title;
            subjectHotVC.myUrl = bgModel.url;
            [self presentViewController:subjectHotVC animated:YES completion:^{
            }];
        }else if (indexPath.row == 2) {
            SubjectMoreVC *subjectMoreVC = [[SubjectMoreVC alloc] init];
            [self presentViewController:subjectMoreVC animated:YES completion:^{
             }];
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            DiscountBGHotVC *bgHotVC = [[DiscountBGHotVC alloc] init];
            [self presentViewController:bgHotVC animated:YES completion:^{
            }];
        }else if (indexPath.row == 2) {
            DiscountMoreVC *rootVC = [[DiscountMoreVC alloc] init];
            [self presentViewController:rootVC animated:YES completion:^{
            }];
        }
    }
    if (indexPath.section == 2) {
        HotTravelViewController *hotVC = [[HotTravelViewController alloc] init];
        HotTravelNotesModel *model = [self.HotTravelNotesArrayM objectAtIndex:indexPath.row];
        hotVC.myID = model.hotid;
        //模态
        [self presentViewController:hotVC animated:YES completion:^{
            
        }];
    }
}

//轮播图
- (void)addANSlideImage {
    if (_slideView == nil) {
        ANScrollView *scollView = [ANScrollView new];
        scollView.height = 220;
        self.slideView = scollView;
        __block RecommendViewController *recomVC = self;
        self.slideView.myBlock = ^(NSInteger pageNumber){
            recomVC.myPageNumber = pageNumber;
        };
    }
    
//    NSLog(@"====sdfds=a=== %@",self.allArray);
    [self.slideView showInView:self.myTabelView withContents:self.allArray];
    [self addHandleSwipeGesture];
}

//轮播图点击事件
- (void) addHandleSwipeGesture
{
    UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    imageV.frame = CGRectMake(0, 0, WIDTH, 220);
    imageV.backgroundColor = [UIColor clearColor];
    [self.myTabelView addSubview:imageV];
    imageV.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [imageV addGestureRecognizer:tap];
    self.myCompare = YES;
    
    //需要点击几次
    tap.numberOfTapsRequired = 1;
    //需要几根手指来点击
    tap.numberOfTouchesRequired = 1;
}

//轻拍手势
-(void)tapAction:(UITapGestureRecognizer *)tap{
    RecoummendScorollVC *scorollVC = [[RecoummendScorollVC alloc] init];
    SlideModel *model = [self.allArray objectAtIndex:self.myPageNumber];
    scorollVC.myUrl = model.url;
    [self presentViewController:scorollVC animated:YES completion:^{
    }];
}

//下拉刷新
- (void)refreshTests
{
    self.isUpLoading = NO;
    ANScrollView *an = [[ANScrollView alloc] init];
    [an removeTimer];
    [self addHeader];
    [self addFooter];
    [an addTimer];
}

#pragma mark --下拉刷新
- (void)addHeader
{
    __block RecommendViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myTabelView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myTabelView headerBeginRefreshing];
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    __block RecommendViewController *vc = self;
    // 添加上拉刷新尾部控件
    [self.myTabelView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
        [vc.myTabelView footerEndRefreshing];
        [vc.myTabelView headerEndRefreshing];
        [vc.myTabelView reloadData];
        if (vc.nextPage < 7) {
            [vc showAlert:[NSString stringWithFormat:@"刷新到第%ld页",vc.nextPage]];
        }else
        {
        [vc showAlert:@"已经到底部,没有可加载数据!"];
        }
     }];
}

#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{

    self.recommendArrayM = [NSMutableArray array];
    self.allArray = [NSMutableArray array];
    DataHandler *handler1 = [[DataHandler alloc] init];
    [handler1 getRecommend:^(id result) {
        self.HUB = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self.HUB show:YES];
        self.HUB.labelText = @"loading...";
        self.recommendArrayM = [NSMutableArray arrayWithArray:result];
        self.datamodel = [self.recommendArrayM objectAtIndex:0];
        self.allArray = self.datamodel.slide;
        self.discountArrayM = self.datamodel.discount;
        [MBProgressHUD hideHUDForView:self.view animated:YES]; //菊花条
        [self.myTabelView footerEndRefreshing];
        [self.myTabelView headerEndRefreshing];
        [self.myTabelView reloadData];
    } failedHandler:^(NSError *error) {
    }];
    
    if (self.isUpLoading == NO) {
        [self.HotTravelNotesArrayM removeAllObjects];
    }
    
    DataHandler *handler = [[DataHandler alloc] init];
       [handler getHotTravelNotes:nextCursor SucceedHandler: ^(id result) {
         NSMutableArray *arrayTemp = [NSMutableArray arrayWithArray:result];
           for (HotTravelNotesModel *model in arrayTemp) {
               [self.HotTravelNotesArrayM addObject:model];
           }
           [self.myTabelView reloadData];
            } failedHandler:^(NSError *error) {
    }];
}

//刷新后显示对话框
- (void)timerFireMethod:(NSTimer*)theTimer  //弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}

- (void)showAlert:(NSString *) _message{   //时间
    
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}

// Search Bar
- (void)loadSearchBar
{
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    searchBar.placeholder = @"搜索目的地、帖子、特价、穷游er";
    searchBar.barTintColor = [UIColor whiteColor];
    searchBar.delegate = self;
    self.navigationItem.titleView = searchBar;
    self.searchBar = searchBar;
}

- (void)addSearchButtonsWith:(NSArray *)hotList
{
    CGFloat margin = 15;
    CGFloat innerOffset = 40;
    CGSize  offset = CGSizeMake(20, 20);
    CGFloat buttonHeight = 32;
    CGFloat width = self.view.bounds.size.width - 2*margin;
    CGFloat maxX = self.view.bounds.size.width - margin;
    CGFloat x = margin;
    CGFloat y = 64;
    CGRect  frame = CGRectZero;
    
    // add hot label
    CGFloat labelHeight = 25;
    CGFloat separatorLineOffset = 8;
    CGFloat separatorLineHeight = 0.5;
    UIColor *separatorLineColor = [UIColor lightGrayColor];
    frame = CGRectMake(margin, y, width, labelHeight);
    UILabel *hotLabel = [[UILabel alloc] initWithFrame:frame];
    hotLabel.text = @"热门搜索";
    [self.searchMenu addSubview:hotLabel];
    
    y += (labelHeight + separatorLineOffset);
    frame = CGRectMake(margin, y, width, separatorLineHeight);
    UIView *hotLine = [[UIView alloc] initWithFrame:frame];
    hotLine.backgroundColor = separatorLineColor;
    [self.searchMenu addSubview:hotLine];
    
    // add hot buttons
    y += separatorLineOffset;
    UIFont *font = [UIFont systemFontOfSize:20];
    NSDictionary *attribute = @{NSFontAttributeName:font};
    
    for (NSInteger i = 0; i < hotList.count; i++) {
        NSString *title = [hotList objectAtIndex:i];
        CGSize size = [title sizeWithAttributes:attribute];
        
        CGFloat buttonWidth = size.width + innerOffset;
        
        CGRect frame = CGRectZero;
        if (x + buttonWidth > maxX) {
            x = margin;
            y += (offset.height + buttonHeight);
        }
        frame = CGRectMake(x, y, buttonWidth, buttonHeight);
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button addTarget:self action:@selector(searchHotAction:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor colorWithRed:0.282 green:0.780 blue:0.588 alpha:1.00].CGColor;
        button.layer.cornerRadius = buttonHeight/2;
        button.frame = frame;
        
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self.searchMenu addSubview:button];
        
        x += (offset.width + buttonWidth);
//        size.width += innerOffset;
    }
}

- (void)searchHotAction:(UIButton *)button
{
    [self.searchMenu removeFromSuperview];
    self.searchMenu = nil;
    [self.searchBar resignFirstResponder];
}

- (void)showSearchMenu
{
    CGFloat width = self.view.bounds.size.width;
    CGFloat height = self.view.bounds.size.height;
    CGRect originalFrame = CGRectMake(0, height, width, height);
    UIView *menu = [[UIView alloc] initWithFrame:originalFrame];
    menu.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:menu];
    self.searchMenu = menu;
    
    DataHandler *handler = [DataHandler new];
    [handler getSearchHistory:^(id result) {
        NSArray *list = (NSArray *)result;
        [self addSearchButtonsWith:list];
    } failedHandler:^(NSError *error) {
        
    }];
    [UIView animateWithDuration:0.6 animations:^{
        menu.frame = CGRectMake(0, 0, width, height);
    } completion:^(BOOL finished) {
        [self.searchMenu becomeFirstResponder];
    }];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self showSearchMenu];
    return YES;
}

@end
